package com.enhanced.mqtt.client;

import com.enhanced.mqtt.manager.EmqxServerManager;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.util.Scanner;

/**
 * 基础MQTT客户端示例
 * 演示基本的连接、订阅和发布功能
 */
public class BasicMqttClient {
    
    private static final String BROKER_URL = "tcp://localhost:1883";
    private static final String TOPIC = "test/topic";
    private static final int QOS = 1;
    
    /**
     * 主方法入口
     */
    public static void main(String[] args) {
        try {
            runDemo(new Scanner(System.in));
        } catch (Exception e) {
            System.out.println("MQTT错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 运行演示，使用外部传入的Scanner
     * @param scanner 已经打开的Scanner
     */
    public static void runDemo(Scanner scanner) throws Exception {
        EmqxServerManager manager = null;
        try {
            // 创建MQTT管理器
            manager = EmqxServerManager.createDefault(BROKER_URL);
            
            // 连接服务器
            manager.connectWithDefaultOptions();
            
            // 订阅主题
            manager.subscribe(TOPIC, QOS);
            
            // 交互式发送消息
            System.out.println("请输入要发送的消息，输入'exit'退出：");
            
            String input;
            while (!(input = scanner.nextLine()).equals("exit")) {
                // 发布消息
                manager.publish(TOPIC, input, QOS, false);
                System.out.print("请输入要发送的消息（输入'exit'退出）: ");
            }
            
        } catch (MqttException e) {
            System.out.println("MQTT错误: " + e.getMessage());
            e.printStackTrace();
            throw e;
        } finally {
            // 关闭连接，但不关闭Scanner
            if (manager != null) {
                try {
                    manager.close();
                } catch (Exception e) {
                    System.out.println("关闭连接时发生错误: " + e.getMessage());
                }
            }
        }
    }
} 